<template>
    <view class="shop-add pd-v-24 pd-b-72">
        
        <view class="shop-add__body overflow-h">
            <u--form
                labelWidth="80"
                labelPosition="left"
                :model="form"
                :rules="rules"
                ref="uForm"
            >
                <view class="border8 pd-l-24 bg-white mr-t-20">
                    <u-form-item
                        label="商户名称"
                        prop="nickName"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.nickName"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入商户名称"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="登录账号"
                        prop="userName"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.userName"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入登录账号"
                            :disabled="props.shopId != ''"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="手机号"
                        prop="phonenumber"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.phonenumber"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入手机号"
                        ></u--input>
                    </u-form-item>
                </view>


                <view class="border8 pd-v-24 pd-h-24 bg-white mr-t-20">
                    <view class="flex flex-center">
                        <view class="font26 lh-28 color-default bold">
                            管理门店
                        </view>
                    </view>
                    <u-form-item prop="storeList">
                        <view class="flex flex-center bg-default pd-v-12">
                            <u-checkbox-group v-model="allChecked" @change="allCheckedChange">
                                <u-checkbox name="allChecked" shape="circle"></u-checkbox>
                            </u-checkbox-group>
                            <view class="flex-1 font24 lh-28 color-info txt-center">
                                门店名称
                            </view>
                            <view class="flex-1 font24 lh-28 color-info txt-center">
                                设备数量
                            </view>
                            <view class="flex-1 font24 lh-28 color-info txt-center">
                                分佣比例
                            </view>
                        </view>
                        <u-checkbox-group v-model="checkList" @change="checkboxChange"> 
                            <scroll-view scroll-y style="height:480rpx">
                                    <view class="flex flex-center pd-v-12 pd-h-8 mr-t-10" v-for="(item,index) in storeList" :key='index+"key"'>
                                        
                                        <u-checkbox :name="item.id" shape="circle"></u-checkbox>
                                        <view class="flex-1 font24 lh-28 color-default txt-center">
                                            {{item.name}}
                                        </view>
                                        <view class="flex-1 font24 lh-28 color-default txt-center">
                                            {{item.deviceCount}}
                                        </view>
                                        <view class="flex-1 flex flex-center flex-j-center">
                                            <u--input :customStyle="{height:'56rpx',padding:'12rpx',width:'160rpx',boxSizing:'border-box'}" placeholder="分佣比例" :suffixIconStyle="{fontSize:'22rpx'}" suffixIcon="%" fontSize="11"
                                                v-model="item.commissionSharingRatio"
                                                @change="inputChange(item)"
                                            >
                                            </u--input>
                                        </view>
                                    </view>
                            </scroll-view>
                        </u-checkbox-group>
                    </u-form-item>
                      
                </view>

                <view class="border8 pd-l-24 bg-white mr-t-20">
                    <u-form-item
                        label="成本分摊"
                        borderBottom
                        prop="costStatus"
                    >
                        
                        <u-radio-group
                            v-model="form.costStatus"
                        >
                            <u-radio
                                :label="'开启'"
                                name="1"
                            >
                            </u-radio>
                            <u-radio
                                :label="'关闭'"
                                name="0"
                            >
                            </u-radio>
                        </u-radio-group>
                    </u-form-item>
                    <u-form-item label="分摊规则" v-if="form.costStatus=='1'">
                        <view class="flex flex-center">
                            <text class="font24 lh-28 color-note pd-v-8">
                                从
                            </text>
                            <view class="">
                                <u-form-item
                                    prop="shareRulesOrder"
                                >
                                    <u--input
                                        border="none"
                                        :customStyle="{padding:'0 8rpx',background:'#f5f5f5',width:'60rpx'}"
                                        v-model="form.shareRulesOrder"
                                    ></u--input>
                                </u-form-item>
                            </view>
                            <text class="font24 lh-28 color-note pd-v-8">
                                个订单之后分摊
                            </text>
                            
                            <view class="">
                                <u-form-item
                                    prop="shareRulesAmountPercentage"
                                >
                                    <u--input
                                        border="none"
                                        :customStyle="{padding:'0 8rpx',background:'#f5f5f5',width:'60rpx'}"
                                        v-model="form.shareRulesAmountPercentage"
                                    ></u--input>
                                </u-form-item>
                            </view>
                            <text class="font24 lh-28 color-note pd-v-8">
                               %
                            </text>
                          
                        </view>
                    </u-form-item>
                </view>

                <view class="border8 pd-l-24 bg-white mr-t-20">
                    <u-form-item
                        label="账号状态"
                        borderBottom
                        prop="status"
                    >
                        
                        <u-radio-group
                            v-model="form.status"
                        >
                            <u-radio
                                :label="'开启'"
                                name="0"
                            >
                            </u-radio>
                            <u-radio
                                :label="'关闭'"
                                name="1"
                            >
                            </u-radio>
                        </u-radio-group>
                    </u-form-item>
                    <u-form-item
                        label="提现"
                        borderBottom
                        prop="isWithdrawal"
                    >
                        
                        <u-radio-group
                            v-model="form.isWithdrawal"
                        >
                            <u-radio
                                :label="'开启'"
                                name="1"
                            >
                            </u-radio>
                            <u-radio
                                :label="'关闭'"
                                name="0"
                            >
                            </u-radio>
                        </u-radio-group>
                    </u-form-item>
                    <u-form-item
                        label="查看订单"
                        borderBottom
                        prop="isViewOrder"
                    >
                        
                        <u-radio-group
                            v-model="form.isViewOrder"
                        >
                            <u-radio
                                :label="'开启'"
                                name="1"
                            >
                            </u-radio>
                            <u-radio
                                :label="'关闭'"
                                name="0"
                            >
                            </u-radio>
                        </u-radio-group>
                    </u-form-item>
                </view>


                <view class="mr-t-40 flex flex-center flex-j-center">
                    <u-button shape="circle"  :customStyle="{height:'88rpx',width:'600rpx'}" color="#35BE65"  text="确认" @click="submit"></u-button>
                </view>
                  
            </u--form>
        </view>
          

        <view class="shop-add__footer">
            
              
              
        </view>
          
          
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick,defineProps } from 'vue';
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';


import { merchantList, merchantUpdate, merchantQueryById,merchantDelete,listForMerchantOfAdd,listForMerchantOfUpdate,getStoreIdByMerchantId,merchantAdd } from '@/api/proxy.js'

const props = defineProps({
    shopId: {
        type: String,
        default: ''
    }
})

const store = useStore();
const form = ref({
    nickName: undefined,
    userName: undefined,
    address:undefined,
    password:'123456',
    phonenumber:undefined,
    roleIds:[100],
    storeList:[],
    costStatus:undefined,
    status:undefined,
    isWithdrawal:undefined,
    isViewOrder:undefined,
    shareRulesOrder:undefined,
    shareRulesAmountPercentage:undefined
});
const uForm = ref(null);
const rules = ref({
    nickName: [
        {
            required: true,
            message: '请输入商户名称',
            trigger: ['blur','change']
        }
    ],
    userName: [
        {
            required: true,
            message: '请输入登录账号',
            trigger: ['blur','change']
        }
    ],
    phonenumber: [
        {
            message: '请输入手机号',
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                if (!value) {
                    callback('请输入手机号');
                    return false;
                } else if (!/^1[3-9]\d{9}$/.test(value)) {
                    callback('请输入正确的手机号');
                    return false;
                } else {
                    callback();
                }
            }
        }
    ],
    storeList: [
        {
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                if (value.length === 0) {
                    callback('请选择管理门店');
                    return false;
                } else {
                    callback();
                }
            }
        }
    ],
    costStatus: [
        {
            required: true,
            message: '请选择成本分摊',
            trigger: ['blur','change']
        }
    ],
    status: [
        {
            required: true,
            message: '请选择账号状态',
            trigger: ['blur','change']
        }
    ],
    isWithdrawal: [
        {
            required: true,
            message: '请选择提现庄涛',
            trigger: ['blur','change']
        }
    ],
    isViewOrder: [
        {
            required: true,
            message: '请选择查看订单状态',
            trigger: ['blur','change']
        }
    ],
    shareRulesOrder: [
        {
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                if(form.value.costStatus) {
                    
                    if (!value) {
                        callback('请输入订单规则');
                        return false;
                    } else {
                        callback();
                    }
                } else {
                    callback()
                }
            }
        }
    ],
    shareRulesAmountPercentage: [
        {
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                if(form.value.costStatus) {
                    
                    if (!value) {
                        callback('请输入分摊比例');
                        return false;
                    } else {
                        callback();
                    }
                } else {
                    callback()
                }
            }
        }
    ]
    
})

const storeList = ref([]);

const allChecked = ref([])
const checkList = ref([]);

onReady(() => {
    setRules()
})

onShow(() => {
    
})

onLoad(() => {
    if(props.shopId) {
        getListForMerchantOfUpdate()
        getGetStoreIdByMerchantId()
        getMerchantQueryById()
    } else {
        getListForMerchantOfAdd()
    }

})

const getMerchantQueryById = () => { 
    merchantQueryById({userId:props.shopId}
    ).then(res => {
        if(res.code == 200) {
            form.value = {...form.value,...res.data};
        }
    })
}


const allCheckedChange = (e) => {
    if(e.length) {
        checkList.value = [];
        storeList.value.forEach((item) => {
            checkList.value.push(item.id);
        });
        form.value.storeList = storeList.value;
    } else {
        checkList.value = [];
        form.value.storeList = []
    }
}

const checkboxChange = (e) => {
    console.log(e,'EEEEEEEEEEEEE')
    let list = []
    storeList.value.forEach((item) => {
        if(e.includes(item.id)) {
            list.push(item)
        }
    });

    form.value.storeList = list;

    if(e.length == storeList.value.length) {
        allChecked.value = ['allChecked']
    } else {
        allChecked.value = []
    }
}
const getGetStoreIdByMerchantId = () => {
    getStoreIdByMerchantId({
        merchantId:props.shopId
    }).then(res => {
        if (res.code === 200) {
            res.data.forEach((item) => {
                checkList.value.push(item.id);
            });
            form.value.storeList = res.data;
        }
    })
}


const getListForMerchantOfAdd = () => {
    listForMerchantOfAdd({
        pageSize: 9999,
        pageNum: 1,
        merchantId:props.shopId
    }).then(res => {
        if (res.code === 200) {
          res.rows.forEach((item) => {
            if (item.commissionSharingRatio == null) {
              item.commissionSharingRatio = undefined;
            }
          });
          storeList.value = res.rows;
        }
    })
}


const getListForMerchantOfUpdate = () => {
    listForMerchantOfUpdate({
        pageSize: 9999,
        pageNum: 1,
        merchantId: props.shopId
    }).then(res => {
        if (res.code === 200) {
          res.rows.forEach((item) => {
            if (item.commissionSharingRatio == null) {
              item.commissionSharingRatio = undefined;
           }
          })
          storeList.value = res.rows;
        }
    })
}

const setRules = () => {
    uForm.value.setRules(rules.value);
}


const submit = () => {
    uForm.value.validate().then(res => {
        console.log(res,'res')
        let params = {...form.value};
        console.log(form.value)
        

        if(props.shopId) {
            params.storeList = form.value.storeList.map(item => {
                return {
                    commissionSharingRatio:item.commissionSharingRatio,
                    storeId:item.id,
                    deviceCount:item.deviceCount,
                    name:item.name
                }
            });
            merchantUpdate(params).then(res => { 
                if(res.code == 200) {
                    uni.showToast({
                        title: '编辑成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    },1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        } else {
            
            params.storeList = form.value.storeList.map(item => {
                return {
                    commissionSharingRatio:item.commissionSharingRatio,
                    storeId:item.id,
                    deviceCount:item.deviceCount,
                    name:item.name
                }
            });
            merchantAdd(params).then(res => { 
                if(res.code == 200) {
                    uni.showToast({
                        title: '添加成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    },1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        }
    }).catch(err => {
        console.log(err,'eeeeeeeeeeeeeeeee')
    })
}

const inputChange = (item) => {
    let list = []
    storeList.value.forEach((item) => {
        if(checkList.value.includes(item.id)) {
            list.push(item)
        }
    });

    form.value.storeList = list;
}

</script>

<style scoped lang="scss">
.shop-add {
    background: #F7F7F7;
    min-height:100vh;
    
    ::v-deep .u-form-item__body__right__message {
        margin-left:0!important;
    }

    .close-btn {
        right:-10rpx;
        top:0;
    }
}
</style>
